<?php

namespace app\shop\model;

header("Content-type:text/html;charset=utf-8");

use app\shop\model\unionpay\AppConfig;
use app\shop\model\unionpay\AppUtil;
use app\shop\model\unionpay\Test;


class RefundPayModel
{

    // /**
    //  * 构造函数
    //  *
    //  * @access  public
    //  * @param
    //  * @return void
    //  */
    // function __construct($request)
    // {
    //     // $request = array();
    //     $this->scanqrpay($request);
    //     date_default_timezone_set('PRC');
    //     define('BASE_PATH', str_replace('\\', '/', realpath(dirname(__FILE__) . '/')) . "/");
    // }
    
    /**
     *  统一被扫接口	
     */
    public function scanqrpay($request)
    {
        // echo "来了";echo "<br/>";
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        $terminfo = [
            'devicetype' => 11,
            'termno'     => $request['termno'],
            'longitude'  => $request['longitude'],
            'latitude'   => $request['latitude'],
            'termsn'     => '',
        ];

        $private_key = $request['private_key'];

        $params = array();
		// $params["cusid"] = AppConfig::CUSID;
        // $params["appid"] = AppConfig::APPID;
        // $params["version"] = AppConfig::APIVERSION;
        $params["cusid"] = $request['cusid'];
        $params["appid"] = $request['appid'];
        $params["version"] = '11';
        $params["trxamt"] = $request['pay_amount']*100;
        $params["reqsn"] = $request['refund_order_no'];
        $params["body"] = '';
        $params["remark"] = $request['description'];
        $params["authcode"] = $request['authcode'];
        $params['terminfo'] = json_encode($terminfo);
        // $params["limit_pay"] = 'no_credit'; // 
        $params["randomstr"] = md5($request['refund_order_no']);
        $params["signtype"] ='RSA';
        $params["sign"] = urlencode(AppUtil::Sign($params,$private_key));//签名 
        $paramsStr = AppUtil::ToUrlParams($params);
        $url = AppConfig::APIURL . "/scanqrpay";
        $rsp = $this->cur_request($url, $paramsStr);
        $rspArray = json_decode($rsp,true); 

        // echo "<pre>";
        // print_r($rspArray);
        // echo "</pre>";
        // $res = AppUtil::validSign($rspArray);
        // echo "结果：".$res;
        // exit;

        if(AppUtil::validSign($rspArray)){
            
            $result = $this->getApiResult($rspArray,$request);

        }else{
            $result['code'] = '9999';
            $result['msg'] = '验签错误';
            // 验签错误，请重新提交;
            // return '1';
        }

        // var_dump($result);exit;
        return $result;
        // exit;
    }

    /**
     *  统一支付接口	
     */
    public function pay($request){
        
        if($request['type'] == 'WeChat'){
            $payType = ['W01'];
        }

        if($request['type'] == 'Alipay'){
            $payType = ['A01'];
        }

        $private_key = $request['private_key'];

        $params = array();

        // 统一支付接口
        $params["cusid"] = $request['cusid'];
        $params["appid"] = $request['appid'];
		$params["version"] = '11';
		$params["orgid"] = '';
		$params["trxamt"] = $request['pay_amount']*100;
		$params["reqsn"] = $request['refund_order_no'];
		$params["paytype"] = $payType;
		$params["body"] = '';
		$params["remark"] = $request['description'];
		$params["validtime"] = 11;
		$params["notify_url"] = 'http://burn.178590.com/shop/pay/get_pay_res';
		$params["limit_pay"] ='';
        $params["validtime"] = '10';
		$params["randomstr"] = md5($request['refund_order_no']);
		$params["signtype"] = 'RSA';
        $params["front_url"] ='';
		$params["sign"] = urlencode(AppUtil::Sign($params,$private_key));//签名 
        $paramsStr = AppUtil::ToUrlParams($params);
		$url = AppConfig::APIURL . "/pay";

        $rsp = $this->cur_request($url, $paramsStr);
        $rspArray = json_decode($rsp,true); 

        return $rspArray;
        
    }


    public function cur_request($url,$jsonData)
    {
        // $ch = curl_init();
	    // curl_setopt($ch, CURLOPT_POST, 1);
	    // curl_setopt($ch, CURLOPT_URL, $url);
	    // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    // // https 支持 - 对认证证书来源的检查
	    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	    // // 请求数据放这里
	    // curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
	    // // head
	    // // curl_setopt($ch, CURLOPT_HTTPHEADER, $head);

        // $response = curl_exec($ch);

        // return $response;

        $ch = curl_init();
		$this_header = array("content-type: application/x-www-form-urlencoded;charset=UTF-8");
		curl_setopt($ch,CURLOPT_HTTPHEADER,$this_header);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		 
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//如果不加验证,就设false,商户自行处理
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		 
		$output = curl_exec($ch);
		curl_close($ch);
		return  $output;
    }

    // 处理交易返回值函数
    public function getApiResult($rspArray,$request)
    {
        // echo "<pre>";
        // print_r($params);
        // echo "</pre>";
        $resCode = $rspArray['trxstatus'];
        $resMsg = $rspArray['errmsg'] ?? '';

        $el = 1;

        while ($resCode == '2000' || $resCode == '2008') {
            $el++;
            
            sleep(10);
            $resCode = $this->query($request,$el);
        }

        // $resCode = $rspArray['trxstatus'];
        // $resMsg = $rspArray['errmsg'] ?? '';
        // switch ($resCode)
        // {
        //     case $resCode == '0000': // 交易成功
        //         $resMsg = '交易成功';
        //         break;
        //     case $resCode == '1001': // 交易不存在
        //         $resMsg = '交易不存在';
        //         break;
        //     case $resCode == '2000': // 等待用户支付
        //         $resMsg = '等待用户支付';

        //         sleep(3);
        //         // 发送交易差送请求
        //         $checkRes = $this->query($params,$prKey);
        //         // exit;
        //         break;
        //     case $resCode > '3000': // 交易失败
        //         $resMsg = $resMsg;
        //         break; 
        //     default:
        //         break;
        // }

        if($resCode=='8888'){
            $resMsg = '支付已超时，请重新发起支付！';
        }

        if($resCode == '3045'){
            $resMsg = '请重新申请支付';
        }
        

        $data['code'] = $resCode;
        $data['msg'] = $resMsg;

        // echo "<pre>";
        // print_r($data);
        // echo "</pre>";
        // exit;

        return $data;

    }

    // 交易查询接口
    public function query($request,$el)
    {
       
        $private_key = $request['private_key'];

        $params = array();
        $params['cusid']     = $request['cusid'];
        $params['appid']     = $request['appid'];
        $params['version']   = '11';
        $params['reqsn']     = $request['refund_order_no'];
        $params['randomstr'] = md5($request['refund_order_no']);
        $params['signtype']  = 'RSA';
        $params['sign']      = urlencode(AppUtil::Sign($params,$private_key));//签名 

        // echo "请求查询<br/>";
        
        // exit;

        $paramsStr = AppUtil::ToUrlParams($params);
	    $url = AppConfig::APIURL . "/query";
	    $rsp = $this->cur_request($url, $paramsStr);

        $rspArray = json_decode($rsp, true); 

	    if(AppUtil::validSign($rspArray)){
	    	// echo "验签正确,进行业务处理";

            if($el>=6){
                // echo "这是第".$el."次查询，支付超时,交易已关闭！！";

                $this->closepay($request);

                // $resData['code'] = '8888';
                
                return '8888'; // 支付超时
            }else{
                return $rspArray['trxstatus'];
            }

            // exit;

	    }
    }


    // 关闭通联订单
    public function closepay($request){

        $private_key = $request['private_key'];

        $params = array();
        $params['cusid']     = $request['cusid'];
        $params['appid']     = $request['appid'];
        $params['version']   = '11';
        $params['oldreqsn']  = $request['refund_order_no'];
        $params['randomstr'] = md5($request['refund_order_no']);
        $params['signtype']  = 'RSA';
        $params['sign']      = urlencode(AppUtil::Sign($params,$private_key));//签名 

        // echo "请求查询<br/>";
        
        // exit;

        $paramsStr = AppUtil::ToUrlParams($params);
	    $url = AppConfig::APIURL . "/close";
	    $rsp = $this->cur_request($url, $paramsStr);

        $rspArray = json_decode($rsp, true); 

    }

    // 订单退款接口
    public function cancel($request)
    {

        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        $private_key = $request['private_key'];

        $params = array();
	  	$params["cusid"] = $request['cusid'];
	    $params["appid"] = $request['appid'];
	    $params["version"] = '11';
	    $params["trxamt"] = $request['pay_amount']*100; // 交易金额
	    $params["reqsn"] = $request['reqsn']; // 订单号
	    $params["signtype"] ='RSA';
	    $params["oldreqsn"] = $request['refund_order_no']; // 原来订单号
	    $params["randomstr"] = md5($request['refund_order_no']); //
        $params["sign"] = urlencode(AppUtil::Sign($params,$private_key));//签名  
	    $paramsStr = AppUtil::ToUrlParams($params);
	    $url = AppConfig::APIURL . "/cancel";
	    // $rsp = request($url, $paramsStr);
		// echo "请求返回:".$rsp;
	    // echo "<br/>";

        $rsp = $this->cur_request($url, $paramsStr);
        $rspArray = json_decode($rsp,true); 

        // echo "<pre>";
        // print_r($rspArray);
        // echo "</pre>";
        // $res = AppUtil::validSign($rspArray);
        // echo "结果：".$res;
        // exit;
	    // $rspArray = json_decode($rsp,true); 
	    if(AppUtil::validSign($rspArray)){
	    	// echo "验签正确,进行业务处理";
            return $rspArray;
	    }
    }

    public function payh5($request)
    {
        $private_key = $request['private_key'];

        $params = array();
        $params["cusid"] = $request['cusid'];
        $params["appid"] = $request['appid'];
        $params["version"] =  '12';
        $params["randomstr"] = md5($request['refund_order_no']);
        $params["trxamt"] = $request['pay_amount']*100;
        $params["reqsn"] = $request['refund_order_no'];
        $params["charset"] = 'UTF-8'; // 1
        $params["returl"] = 'https://test.allinpaygd.com/JWeb/recparams.jsp'; // 1
        $params["notify_url"] = 'http://burn.178590.com/shop/pay/get_pay_res';
        $params["body"] = '心意初八'; // 1
        $params["validtime"] = '10';
        $params["signtype"] = 'RSA';

        echo $private_key;

        echo "<pre>";
        print_r($params);
        echo "</pre>";
        exit;
        $params["sign"] = urlencode(AppUtil::Sign($params,$private_key));//签名 

        $url = "https://syb.allinpay.com/apiweb/h5unionpay/unionorder";

        $rsp = $this->send_post($url, $params);

        var_dump($rsp);
    }



    public function send_post($url,$post_data)
    {
        $postdata = http_build_query($post_data);
        $options = [
            'http' => [
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            ]
        ];

        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        
        return $result;
    }

    // 终端信息采集接口
    public function addterm($request){

        // return $request;

        $private_key = $request['private_key'];

        $params = array();
        $params["cusid"] = $request['cusid'];
        $params["appid"] = $request['appid'];
        $params["termno"] = $request['termno'];
        $params["version"] = '11';
        $params['devicetype'] = '11';
        $params['operation'] = '00';
        $params['termstate'] = '00';
        $params["termaddress"] = $request['termaddress'];
        $params["signtype"] ='RSA';
        $params["sign"] = urlencode(AppUtil::Sign($params,$private_key));//签名 
        $paramsStr = AppUtil::ToUrlParams($params);
        $url = "https://vsp.allinpay.com/cusapi/merchantapi/addterm";
        $rsp = $this->cur_request($url, $paramsStr);
        $rspArray = json_decode($rsp,true); 

        return $rspArray;
        // echo "<pre>";
        // print_r($rspArray);
        // echo "</pre>";
        // $res = AppUtil::validSign($rspArray);
        // echo "结果：".$res;
        // exit;
    }

}
